import logging
import platform
import os
import threading

import numpy as np

def setup_logging():
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(module)s - %(message)s',
        handlers=[
            logging.FileHandler("voice_assistant.log"),
            logging.StreamHandler()
        ]
    )
    return logging.getLogger("VoiceAssistant")

def play_notification_sound():
    """播放提示音"""
    try:
        # Windows系统
        if platform.system() == "Windows":
            import winsound
            winsound.Beep(1000, 200)  # 1000Hz, 200ms
            
        # macOS系统
        elif platform.system() == "Darwin":
            os.system('afplay /System/Library/Sounds/Ping.aiff')
            
        # Linux系统
        else:
            os.system('aplay -q /usr/share/sounds/speech-dispatcher/test.wav')
            
    except Exception as e:
        logging.error(f"无法播放提示音: {str(e)}")

def run_in_thread(target):
    """在新线程中运行函数"""
    thread = threading.Thread(target=target, daemon=True)
    thread.start()
    return thread

def calculate_rms(audio_data):
    """计算音频的RMS值"""
    if len(audio_data) > 0:
        squared = np.square(audio_data.astype(np.float32))
        mean_val = np.mean(squared)
        return np.sqrt(mean_val) if mean_val > 0 else 0
    return 0

def min_max_scaled(value, min_val, max_val):
    """限制值在指定范围内"""
    return max(min_val, min(max_val, value))